/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import entities.Submission;
import entities.TestResult;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

/**
 *
 * @author ryuju
 */
@MessageDriven(mappedName = "jms/TestResultMsgQueue", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class TestResultMsgHandler implements MessageListener {
    @EJB
    private SubmissionManager submissionManager;
    
    public TestResultMsgHandler() {
    }
    
    @Override
    public void onMessage(Message message) {
        // TODO: handle TestResult
        // get submission
        // set submission property about TestResult
        // store submission
        ObjectMessage om = (ObjectMessage) message;
        TestResult tr;
        
        try {
            tr = (TestResult) om.getObject();
            Logger.getLogger(SubmissionManager.class.getName()).log(Level.INFO, "[SUBMIT] receive test result from TestResultQueue ID: " + tr.getSubmitID());
            Long submitID = tr.getSubmitID();
            Submission submitted = submissionManager.getSubmittedItem(submitID);
            if(null != submitted)
            {
                // set submitted's property and judge.
                submissionManager.judge(submitted, tr);
            }
            else
            {
                Logger.getLogger(TestResultMsgHandler.class.getName()).log(Level.SEVERE, null, "Can not find subbmited submission");
            }
        } catch (JMSException ex) {
            Logger.getLogger(TestResultMsgHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
  
    }
}
